/* eslint-disable */
// @ts-check
const request = require('request');
const fs = require('fs');
const { baseConfig, configs } = require('./configs');
const cliProgress = require('cli-progress');

const download = async (url, savePath) => {
  const bar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);

  let current = 0;
  return new Promise((resolve, reject) => {
    request(url)
      .on('response', (response) => {
        const total = parseInt(response.headers['content-length']) || 0;
        bar.start(total, 0);
      })
      .on('data', (data) => {
        current += data.length;
        bar.update(current);
      })
      .on('close', (err) => {
        if (err) {
          reject(err);
          return;
        }

        bar.stop();

        resolve();
      })
      .pipe(fs.createWriteStream(savePath))
  });
}

/**
 * 下载 swagger json
 */
const main = async () => {
  const apiName = process.env.API_NAME;
  if (!apiName) { throw new Error('没有传入node环境变量"API_NAME"。') }

  const config = configs[apiName];
  if (!config) { throw new Error(`无法找到服务"${apiName}"的配置。`); }

  if(config.swaggerUrl !== ''){
    console.log(`开始下载服务"${apiName}"的原始 swagger json。`);
    await download(config.swaggerUrl, baseConfig.swaggerPath(apiName));
    console.log(`--- 下载原始 swagger json 完毕\n`);
  }

  console.log(`开始下载服务"${apiName}"的 yapi json。`);
  await download(config.remoteUrl, baseConfig.yapiPath(apiName));
  console.log(`--- 下载 yapi json 完毕\n`);
};

main().catch(err => {
  console.error(err);
  process.exit(1);
});
